package org.example;

import model.Product;
import service.ProductSorters;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Comparator;
import java.util.Collections;

public class ConsoleShop {

    private final ProductService productService = new ProductService();
    // 购物车：key是商品ID，value是购买数量
    private final Map<String, Integer> shoppingCart = new HashMap<>();
    private final Scanner scanner = new Scanner(System.in);

   /** public void start() {
        System.out.println("=== 商城系统启动 ===");
        System.out.println("当前商品数量: " + productService.getProductCount());
        System.out.println("备份状态: " + productService.getBackupInfo());
        try{
        while (true) {
            showMenu();
            int choice = scanner.nextInt();
            scanner.nextLine(); // 消费掉换行符

            switch (choice) {
                case 1:
                    browseProducts(null);
                    break;
                case 2:
                    addToCart();
                    break;
                case 3:
                    showSortedProducts();

                    break;
                case 4:
                    viewCart();

                    break;
                case 5:
                    checkout();
                    break;
                case 6:
                    exit(); // 在程序返回前调用 productService.saveData()
                    break;
                case 99: // 隐藏管理员选项 - 数据备份
                    backupData();
                default:
                    System.out.println("无效的选项，请重新输入！");
            }
        }
        } finally {
            // 确保扫描器在程序结束时关闭
            if (scanner != null) {
                scanner.close();
            }
        }
    }
*/

   public void start() {
       System.out.println("=== 商城系统启动 ===");
       System.out.println("当前商品数量: " + productService.getProductCount());
       System.out.println("备份状态: " + productService.getBackupInfo());

       try {
           while (true) {
               showMenu();
               String input = scanner.nextLine().trim();  // 统一使用 nextLine()

               if (input.isEmpty()) {
                   System.out.println("请输入有效的数字选项！");
                   continue;
               }

               // 检查输入是否为数字
               if (!input.matches("\\d+")) {
                   System.out.println("请输入有效的数字选项！");
                   continue;
               }

               int choice = Integer.parseInt(input);  // 手动转换为整数

               switch (choice) {
                   case 1:
                       browseProducts(null);
                       break;
                   case 2:
                       addToCart();
                       break;
                   case 3:
                       showSortedProducts();
                       break;
                   case 4:
                       viewCart();
                       break;
                   case 5:
                       checkout();
                       break;
                   case 6:
                       exit();
                       return; // 只有退出时才返回
                   case 99: // 隐藏管理员选项 - 数据备份
                       backupData();
                       break;
                   default:
                       System.out.println("无效的选项，请重新输入！");
               }
           }
       } catch (Exception e) {
           System.err.println("程序出现异常: " + e.getMessage());
           e.printStackTrace();
       } finally {
           // 确保扫描器在程序结束时关闭
           if (scanner != null) {
               scanner.close();
           }
       }
   }

    private void showMenu() {
        System.out.println("\n jjjj欢迎来到商城---- ");
        System.out.println("1. 浏览所有商品");
        getPrintln();
        System.out.println("3.自定义排序浏览商品");
        System.out.println("4. 查看购物车");
        System.out.println("5.结账");
        System.out.println("6. 退出");
        System.out.print("请输入您的选择: ");
        System.out.println("test");
    }

    private void backupData() {
        System.out.println("\n=== 数据备份功能 ===");
        System.out.println("正在备份数据文件...");

        boolean success = productService.backupData();
        if (success) {
            System.out.println("✅ 数据备份完成！");
        } else {
            System.out.println("❌ 数据备份失败！");
        }

        // 显示备份文件信息
        System.out.println("当前备份状态: " + productService.getBackupInfo());
    }

    private static void getPrintln() {
        System.out.println("2. 添加商品到购物车");
    }

    private void browseProducts(Comparator<Product>comparator) {
        System.out.println("\n--- 商品列表 ---");
        List<Product> products = productService.getAllProducts();
        if (products.isEmpty()) {
            System.out.println("商店里还没有商品。");
        } else {
            if (comparator == null) {
                Collections.sort(products); // 使用 Product 的 compareTo 方法
            } else {
                Collections.sort(products, comparator);
            }
            products.forEach(System.out::println);
        }
    }


    private void showSortedProducts() {
        System.out.println("\n=== 选择排序方式 ===");
        System.out.println("1. 按价格从低到高");
        System.out.println("2. 按价格从高到低");
        System.out.println("3. 按库存从多到少");
        System.out.println("4. 默认排序（按ID）");
        System.out.print("请选择排序方式: ");

        int sortChoice = scanner.nextInt();
        scanner.nextLine();

        Comparator<Product> comparator = null;
        String sortDescription = "";

        switch (sortChoice) {
            case 1:
                comparator = ProductSorters.BY_PRICE_ASC;
                sortDescription = "价格从低到高";
                break;
            case 2:
                comparator = ProductSorters.BY_PRICE_DESC;
                sortDescription = "价格从高到低";
                break;
            case 3:
                comparator = ProductSorters.BY_STOCK_DESC;
                sortDescription = "库存从多到少";
                break;
            case 4:
                sortDescription = "默认排序（按ID）";
                break;
            default:
                System.out.println("无效选择，使用默认排序。");
                sortDescription = "默认排序（按ID）";
        }

        System.out.println("\n--- 商品列表（" + sortDescription + "）---");
        browseProducts(comparator);
    }




    private void addToCart() {
        System.out.print("请输入要添加的商品ID: ");
        String productId = scanner.nextLine();
        Product product = productService.findProductById(productId);

        if (product == null) {
            System.out.println("错误：找不到该商品！");
            return;
        }
        if (product.getStock() <= 0) {
            System.out.println("抱歉，该商品已售罄。");
            return;
        }

        System.out.print("请输入购买数量: ");
        int quantity = scanner.nextInt();
        scanner.nextLine(); // 消费换行符

        if (quantity <= 0) {
            System.out.println("错误：购买数量必须为正数！");
            return;
        }
        if (quantity > product.getStock()) {
            System.out.println("错误：库存不足！当前库存为 " + product.getStock());
            return;
        }

        // 将商品加入购物车，如果已存在则累加数量
        shoppingCart.put(productId, shoppingCart.getOrDefault(productId, 0) + quantity);
        System.out.println("成功将 '" + product.getName() + "' 添加到购物车！");
    }

    private void viewCart() {
        System.out.println("\n--- 我的购物车 ---");
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车是空的，快去逛逛吧！");
            return;
        }

        double total = 0.0;
        for (Map.Entry<String, Integer> entry : shoppingCart.entrySet()) {
            String productId = entry.getKey();
            Integer quantity = entry.getValue();
            Product product = productService.findProductById(productId);
            if (product != null) {
                double subtotal = product.getPrice() * quantity;
                System.out.printf("商品: %-20s | 单价: ¥%-8.2f | 数量: %-3d | 小计: ¥%.2f\n",
                        product.getName(), product.getPrice(), quantity, subtotal);
                total += subtotal;
            }
        }
        System.out.println("------------------------------------");
        System.out.printf("总计: ¥%.2f\n", total);
    }

    private void checkout() {
        if (shoppingCart.isEmpty()) {
            System.out.println("购物车为空，无法结账");
            return;
        }

        System.out.println("结账成功!");
        shoppingCart.clear();
        // 结账后自动保存数据
        productService.saveData();
    }
    private void exit() {
        // 退出前保存数据
        System.out.println("\n正在保存数据...");
        productService.saveData();
        System.out.println("数据保存完成！");
        System.out.println("感谢使用商城系统，再见！");
    }
    public static void main (String[]args) {

        new ConsoleShop().start();

    }


    }
